package com.vetalik.autobounce;
import java.io.IOException;
import java.util.Collection;
import java.util.NoSuchElementException;


import javax.servlet.http.*;


import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Blip;
import com.google.wave.api.Event;
import com.google.wave.api.EventType;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;


@SuppressWarnings("serial")
public class AutobounceServlet extends AbstractRobotServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
	}

	@Override
	public void processEvents(RobotMessageBundle rmb) {
		Wavelet wavelet = rmb.getWavelet();
        
	    if (rmb.wasSelfAdded()) {
	      Blip blip = wavelet.appendBlip();
	      TextView textView = blip.getDocument();
	      textView.append("I'm alive!");
	    }
	            
	    for (Event e: rmb.getEvents()) {
	      if (e.getType() == EventType.WAVELET_PARTICIPANTS_CHANGED) {    
	        Collection<String> participants = e.getAddedParticipants();
	        Wavelet w = e.getWavelet();
	        
	        try{
	        	w.removeParticipant(participants.iterator().next());
	        }
	        catch(NoSuchElementException el){
	        	Blip blip = wavelet.appendBlip();
	  	      	TextView textView = blip.getDocument();
	  	      	textView.append("ekarnij babaj");
	        }
	        catch(Exception ex){
	        	Blip blip = wavelet.appendBlip();
	  	      	TextView textView = blip.getDocument();
	  	      	textView.append(ex.getMessage());
	        }
	        Blip blip = wavelet.appendBlip();
	        TextView textView = blip.getDocument();
	        for(String p:w.getParticipants()){
	        	textView.append(p + " : huj ");
	        }
	      }
	    }
		
	}
}
